package com.jamal2362.apktool.preference;

import android.content.Context;
import android.content.DialogInterface;
import android.content.SharedPreferences;
import android.graphics.Bitmap;
import android.graphics.Color;
import android.util.AttributeSet;
import android.view.LayoutInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.LinearLayout;
import android.widget.Spinner;
import android.widget.TextView;
import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.widget.PopupMenu;
import java.io.File;
import com.jamal2362.apktool.R;
import com.jamal2362.apktool.util.FilePicker;
import com.jamal2362.apktool.util.FileUtils;
import com.jamal2362.apktool.util.IconFactory;
import com.jamal2362.apktool.util.Settings;

public class KeystorePreference extends CustomPreference implements AdapterView.OnItemSelectedListener
{
	private Spinner format;
	private EditText key_path;
	private TextView cert;
	private EditText alias;
	private LinearLayout password;
	private EditText storePass;
	private EditText keyPass;
	private ImageButton selectKey;
	private ImageButton selectCert;

	public KeystorePreference(Context ctx, AttributeSet a)
	{
		super(ctx, a);
	}

	@Override
	protected void onClick()
	{
		final Context context = getContext();
		final IconFactory icFactory = new IconFactory(context);
		final LayoutInflater inflater = LayoutInflater.from(context);
		final View view = inflater.inflate(R.layout.keystore, null);
		final AlertDialog.Builder mBuilder = new AlertDialog.Builder(context);
		mBuilder.setView(view);
		mBuilder.setTitle(R.string.signature_file);
		mBuilder.setNegativeButton(R.string.cancel, mClick);
		mBuilder.setPositiveButton(R.string.save, mClick);
		int fcolor = (!Settings.lightTheme ? Color.BLACK : Color.DKGRAY);
		Bitmap folder = icFactory.makeIcon(fcolor, R.drawable.ic_folder, 24, 16, 0);
		format = view.findViewById(R.id.format);
		key_path = view.findViewById(R.id.key_path);
		cert = view.findViewById(R.id.cert);
		alias = view.findViewById(R.id.alias);
		password = view.findViewById(R.id.password);
		storePass = view.findViewById(R.id.storePass);
		keyPass = view.findViewById(R.id.keyPass);
		selectKey = view.findViewById(R.id.keystoreImageButton1);
		selectCert = view.findViewById(R.id.keystoreImageButton2);
		selectKey.setImageBitmap(folder);
		selectCert.setImageBitmap(folder);
		format.setOnItemSelectedListener(this);
		SharedPreferences sp = getSharedPreferences();
		int type = sp.getInt("key_type", 0);
		format.setSelection(type);
		String keyPath = sp.getString("key_path", "");
		key_path.setText(keyPath);
		String cert_or_alias = sp.getString("cert_or_alias", "");
		alias.setText(cert_or_alias);
		String store_pass = sp.getString("store_pass", "");
		storePass.setText(store_pass);
		String key_pass = sp.getString("key_pass", "");
		keyPass.setText(key_pass);
		View.OnClickListener click = new OnClickListener()
		{
			@Override
			public void onClick(final View p1)
			{
				final FilePicker picker = new FilePicker(context);
				Runnable cback = new Runnable()
				{
					@Override
					public void run()
					{
						if (p1.getId() == R.id.keystoreImageButton1)
							key_path.setText(picker.getPath());
						else
							alias.setText(picker.getPath());
					}
				};
				String[] extsKey = null;
				String[] extsCert = null;
				switch (format.getSelectedItemPosition())
				{
					case 0:
						extsKey = new String[]{"jks", "keystore", "key"};
						break;

					case 1:
						extsKey = new String[]{"p12", "pfx"};
						break;

					case 2:
						extsKey = new String[]{"bks"};
						break;

					case 3:
						extsKey = new String[]{"pk8"};
						extsCert = new String[]{"x509.pem"};
						break;
				}
				picker.setCallback(cback);
				picker.setFilter(p1.getId() == R.id.keystoreImageButton1 ? extsKey : extsCert);
				AlertDialog.Builder pbuilder = new AlertDialog.Builder(context);
				pbuilder.setTitle(R.string.mselect);
				pbuilder.setView(picker);
				pbuilder.setPositiveButton(R.string.cancel, null);
				pbuilder.setNeutralButton("/...", null);
				final AlertDialog dialog = pbuilder.create();
				dialog.setOnShowListener(new DialogInterface.OnShowListener() {
						@Override
						public void onShow(DialogInterface dialogInterface)
						{
							Button button = dialog.getButton(AlertDialog.BUTTON_NEUTRAL);
							button.setOnClickListener(new View.OnClickListener() {
									@Override
									public void onClick(View v)
									{
										String[] storages = FileUtils.getStorages(context);
										if (storages == null)
											return;
										PopupMenu menu = new PopupMenu(context, v);
										for (int i = 0; i < storages.length; i++)
										{
											MenuItem mi = menu.getMenu().add(0, (1100 + i), 0, storages[i]);
											mi.setOnMenuItemClickListener(new MenuItem.OnMenuItemClickListener()
												{
													@Override
													public boolean onMenuItemClick(MenuItem m)
													{
														File root = new File(m.getTitle().toString());
														picker.refresh(root);
														return true;
													}
												});
										}
										menu.show();
									}
								});
						}
					});
				picker.setDialog(dialog);
				dialog.show();
			}
		};
		selectKey.setOnClickListener(click);
		selectCert.setOnClickListener(click);
		mBuilder.create().show();
	}

	public DialogInterface.OnClickListener mClick = new DialogInterface.OnClickListener()
	{
		@Override
		public void onClick(DialogInterface dialog, int which)
		{
			if (which == DialogInterface.BUTTON_POSITIVE)
			{
				SharedPreferences.Editor editor = getSharedPreferences().edit();
				editor.putInt("key_type", format.getSelectedItemPosition());
				editor.putString("key_path", key_path.getText().toString());
				editor.putString("cert_or_alias", alias.getText().toString());
				editor.putString("store_pass", storePass.getText().toString());
				editor.putString("key_pass", keyPass.getText().toString());
				editor.commit();
			}
			else if (which == DialogInterface.BUTTON_NEUTRAL)
			{
				SharedPreferences.Editor editor = getSharedPreferences().edit();
				editor.putString("store_pass", "");
				editor.putString("key_pass", "");
				editor.commit();
			}
		}
	};
	

	@Override
	public void onItemSelected(AdapterView<?> p1, View p2, int p3, long p4)
	{
		if (p3 == 3)
		{
			password.setVisibility(View.GONE);
			selectCert.setVisibility(View.VISIBLE);
			cert.setText(R.string.cert_path);
		}
		else
		{
			password.setVisibility(View.VISIBLE);
			selectCert.setVisibility(View.GONE);
			cert.setText(R.string.key_alias);
		}
	}

	@Override
	public void onNothingSelected(AdapterView<?> p1)
	{
	}
}
